<!-- SwipeCell.vue -->
<template>
  <div class="swipeCell" :style="{ height: showImage ? '80px' : '64px' }">
    <div class="container" @touchstart.passive="handleTouchStart" @touchmove.passive="handleTouchMove"
      @touchend.passive="handleTouchEnd" @click="handleClick" ref="swipeCellRef"
      :style="{ transform: `translateX(${currentX}px)` }">
      <!-- 左侧内容 -->
      <div class="left-container">
        <div class="checked-container" v-if="$slots['left-checked']">
          <slot name="left-checked"></slot>
        </div>
        <div class="image-container" v-if="showImage">
          <div class="title-container" v-if="$slots['left-title']">
            <slot name="left-title">商品标题</slot>
          </div>
          <slot name="left-image">
            <img src="https://ww4.sinaimg.cn/mw690/61d7678dgy1i0os88ntcij20w01kw7ig.jpg" alt="商品图片" />
          </slot>
        </div>
        <div class="info-container">
          <div class="title">{{ title }}</div>
          <div class="description">
            {{ description }}
            <div class="count" v-if="count">{{ count }}</div>
          </div>
          <div class="quantity">
            <div class="time">{{ time }}</div>
          </div>
        </div>
      </div>

      <!-- 右侧操作 -->
      <div class="right-container" v-if="hasRightSlot">
        <slot name="right"></slot>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useSlots } from 'vue'

// Props
const props = defineProps({
  title: { type: String, default: '商品标题' },
  description: { type: String, default: '描述信息' },
  time: { type: String, default: '' },
  showImage: { type: Boolean, default: true },
  count: { type: [Number, String], default: 0 }
})

// 创建一个唯一的ID用于标识当前SwipeCell实例
const instanceId = ref(Math.random().toString(36).substring(2, 9))

// 全局SwipeCell管理器
const swipeCellManager = window.swipeCellManager || {
  currentOpenId: null,
  instances: new Map(),

  // 注册实例
  register(id, closeFn) {
    this.instances.set(id, closeFn)
  },

  // 取消注册
  unregister(id) {
    this.instances.delete(id)
    if (this.currentOpenId === id) {
      this.currentOpenId = null
    }
  },

  // 关闭所有实例
  closeAll(excludeId) {
    this.instances.forEach((closeFn, id) => {
      if (id !== excludeId) {
        closeFn()
      }
    })
    this.currentOpenId = excludeId || null
  },

  // 关闭当前打开的实例
  closeCurrent() {
    if (this.currentOpenId) {
      const closeFn = this.instances.get(this.currentOpenId)
      if (closeFn) {
        closeFn()
      }
      this.currentOpenId = null
    }
  }
}

// 将管理器保存到window对象，确保所有实例共享同一个管理器
window.swipeCellManager = swipeCellManager

// Refs
const swipeCellRef = ref(null)
const startX = ref(0)
const currentX = ref(0)
const isDragging = ref(false)
const hasMoved = ref(false)
const isOpen = ref(false)

// 常量
const rightWidth = 60
const moveThreshold = 10 // 判断是否为点击

// Computed
const hasRightSlot = computed(() => !!useSlots().right)

// 关闭当前SwipeCell
const close = () => {
  currentX.value = 0
  isOpen.value = false
  if (swipeCellRef.value) {
    swipeCellRef.value.style.transition = 'transform 0.3s ease'
    swipeCellRef.value.style.transform = 'translateX(0)'
  }
  setTimeout(() => {
    if (swipeCellRef.value) {
      swipeCellRef.value.style.transition = ''
    }
  }, 300)

  // 更新全局状态
  if (swipeCellManager.currentOpenId === instanceId.value) {
    swipeCellManager.currentOpenId = null
  }
}

// 打开当前SwipeCell
const open = () => {
  // 先关闭其他已打开的SwipeCell
  swipeCellManager.closeAll(instanceId.value)

  currentX.value = -rightWidth
  isOpen.value = true
  if (swipeCellRef.value) {
    swipeCellRef.value.style.transition = 'transform 0.3s ease'
    swipeCellRef.value.style.transform = `translateX(-${rightWidth}px)`
  }
  setTimeout(() => {
    if (swipeCellRef.value) {
      swipeCellRef.value.style.transition = ''
    }
  }, 300)

  // 更新全局状态
  swipeCellManager.currentOpenId = instanceId.value
}

// 切换SwipeCell状态
const toggle = () => {
  if (isOpen.value) {
    close()
  } else {
    open()
  }
}

// 点击处理
const handleClick = () => {
  if (!hasMoved.value) {
    if (isOpen.value) {
      close()
    } else {
      // 如果当前未打开，先关闭其他已打开的SwipeCell
      swipeCellManager.closeAll(instanceId.value)
    }
  }
}

// 触摸事件处理
const handleTouchStart = (e) => {
  if (!hasRightSlot.value) return
  isDragging.value = true
  hasMoved.value = false
  startX.value = e.touches[0].clientX

  // 关闭其他已打开的SwipeCell
  swipeCellManager.closeAll(instanceId.value)
}

const handleTouchMove = (e) => {
  if (!isDragging.value || !hasRightSlot.value) return

  const moveX = e.touches[0].clientX
  const diff = startX.value - moveX

  if (Math.abs(diff) > moveThreshold) {
    hasMoved.value = true
    // 注意：由于使用了passive事件监听器，这里不能调用preventDefault()
    // 我们通过CSS的touch-action属性来控制滚动行为
  }

  if (hasMoved.value) {
    currentX.value = Math.max(-rightWidth, Math.min(0, -diff))
  }
}

const handleTouchEnd = () => {
  if (!isDragging.value) return
  isDragging.value = false

  if (!hasMoved.value) {
    // 是点击，不触发滑动
    return
  }

  const threshold = -rightWidth / 2
  if (currentX.value <= threshold) {
    open()
  } else {
    close()
  }

  // 添加过渡动画
  if (swipeCellRef.value) {
    swipeCellRef.value.style.transition = 'transform 0.3s ease'
  }

  setTimeout(() => {
    if (swipeCellRef.value) {
      swipeCellRef.value.style.transition = ''
    }
  }, 300)
}

// 点击外部关闭SwipeCell
const handleOutsideClick = (e) => {
  if (isOpen.value && !swipeCellRef.value.contains(e.target)) {
    close()
  }
}

// 组件挂载时注册实例和添加全局点击事件监听
onMounted(() => {
  swipeCellManager.register(instanceId.value, close)
  document.addEventListener('click', handleOutsideClick)
})

// 组件卸载时取消注册和移除全局点击事件监听
onBeforeUnmount(() => {
  swipeCellManager.unregister(instanceId.value)
  document.removeEventListener('click', handleOutsideClick)
})

// 暴露方法给父组件
defineExpose({
  close,
  open,
  toggle
})
</script>
<style lang="scss" scoped>
/* 保持你原有的样式不变 */
.swipeCell {
  width: 100%;
  height: 80px;
  background-color: transparent;
  position: relative;
  box-sizing: border-box;
  overflow: hidden;
  user-select: none;
  margin-bottom: 5px;

  .container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    touch-action: pan-y;
    /* 允许垂直滚动，禁止水平滚动 */

    .left-container {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      padding: 0 10px;
      position: relative;

      .title-container {
        position: absolute;
        top: 0;
        left: 0;
        font-size: 12px;
        color: #fff;
        padding: 2px 4px;
        border-radius: 4px;
        background: #ff6140;
      }

      .checked-container {
        width: 20px;
        height: 20px;
        border-radius: 50%;
      }

      .image-container {
        width: 50px;
        height: 50px;
        border-radius: $border-radius-full;
        overflow: hidden;
        flex-shrink: 0;
      }

      .info-container {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        flex-direction: column;
        gap: 16px;
        padding: 0 10px;
        position: relative;

        .title {
          font-size: 14px;
          font-weight: bold;
        }

        .description {
          font-size: 14px;
          color: #666;
          @include multi-line-ellipsis(2);
          position: relative;
          overflow: visible;

          .count {
            width: 15px;
            height: 15px;
            background-color: #face16;
            @include absolute-top-right(-2px);
            @include flex-center;
            font-size: $font-size-small;
            border-radius: $border-radius-full;
          }
        }


        .quantity {
          @include absolute-top-right(10px, 10px);
          font-size: 14px;
          color: #999;
        }
      }
    }

    .right-container {
      width: 60px;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      background-color: #ff4949;
      color: #fff;
      font-size: 14px;
    }
  }
}
</style>